"use client"

import { useState, useEffect } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Loader2, FileSpreadsheet, ArrowLeft, Save, CheckCircle, XCircle, AlertCircle } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { canEditByRole, getPermissionDescription } from '@/lib/data-entry-permissions'
import ParameterTable from '@/components/parameter-table'

const PARAMETER_HEADERS = [
  { key: 'sequence', label: '序号', width: 'w-12' },
  { key: 'parameter_name', label: '中文名称', width: 'w-48' },
  { key: 'example_description', label: '示例或属性说明', width: 'w-56' },
  { key: 'data_type', label: '数据类型', width: 'w-24' },
  { key: 'measurement_class', label: '计量类', width: 'w-24' },
  { key: 'measurement_unit', label: '计量单位', width: 'w-24' },
  { key: 'data_source', label: '数据来源', width: 'w-24' },
  { key: 'parameter_value', label: '数据录入', width: 'w-40' }
];

export default function PipingParametersPage() {
  const { toast } = useToast()
  const searchParams = useSearchParams()
  const router = useRouter()
  
  const [tableData, setTableData] = useState<any>(null)
  const [filteredTableData, setFilteredTableData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [selectedFilter, setSelectedFilter] = useState<string>('all')
  const [inputData, setInputData] = useState<Record<string, string>>({})
  const [savedData, setSavedData] = useState<Record<string, string>>({})
  const [isLocked, setIsLocked] = useState(true)
  const [validationResults, setValidationResults] = useState<Record<string, {isValid: boolean, message: string, type: 'success' | 'error' | 'warning'}>>({})
  const [currentUserRole, setCurrentUserRole] = useState<string>('guest')
  const [parameters, setParameters] = useState<any[]>([])
  const [fetchError, setFetchError] = useState<string | null>(null)
  const [measurementUnitMap, setMeasurementUnitMap] = useState<Record<string, string>>({})
  const [isEditing, setIsEditing] = useState(false)
  const [editData, setEditData] = useState<Record<string, string>>({})
  const [originalData, setOriginalData] = useState<Record<string, string>>({})

  // 从URL参数获取信息
  const classificationCode = searchParams.get('code') || ''
  const tableName = searchParams.get('name') || ''
  const type = (searchParams.get('type') as 'naming' | 'position' | 'location' | 'base') || 'base'
  const deviceName = searchParams.get('deviceName') || ''

  // 只用URL参数获取deviceId
  const deviceId = searchParams.get('deviceId') || '';

  // 提取表名缩写（如表 C.2 => C2）
  const extractTableShort = (name: string) => {
    const match = name.match(/表\s*C\.(\d+)/);
    return match ? `C${match[1]}` : '';
  };
  const tableShort = extractTableShort(tableName);
  const uniqueTableId = deviceId && tableShort ? `${deviceId}-${tableShort}` : '';

  // 处理输入数据变化
  const handleInputChange = (rowIndex: number, header: string, value: string) => {
    const key = `${rowIndex}-${header}`
    setInputData(prev => ({
      ...prev,
      [key]: value
    }))
    
    if (filteredTableData && rowIndex < filteredTableData.rows.length) {
      const validation = validateData(value, filteredTableData.rows[rowIndex], filteredTableData.headers)
      setValidationResults(prev => ({ ...prev, [key]: validation }))
    }
  }

  // 保存数据
  const saveData = async () => {
    try {
      console.log('保存数据开始，设备ID:', deviceId, '参数类型:', type);
      console.log('当前输入数据:', inputData);
      console.log('过滤表格数据:', filteredTableData);
      
      // 准备要保存的参数数据
      const parametersToSave = Object.entries(inputData)
        .filter(([key, value]) => value && value.trim() !== '') // 只保存有值的参数
        .map(([key, value]) => {
          const rowKey = key.replace('-数据录入', '');
          
          // 找到对应的参数名称 - 改进查找逻辑
          let parameterName = `参数_${key}`;  // 使用完整key作为fallback
          let rowIndex = -1;
          
          if (filteredTableData?.rows) {
            // 首先尝试将rowKey作为索引
            if (!isNaN(Number(rowKey))) {
              rowIndex = Number(rowKey);
              if (rowIndex >= 0 && rowIndex < filteredTableData.rows.length) {
                const row = filteredTableData.rows[rowIndex];
                // 获取中文名称列（通常是第二列，索引为1）
                const chineseName = row?.[1]?.toString().trim();
                if (chineseName && chineseName !== '' && chineseName !== '—') {
                  parameterName = chineseName;
                }
              }
            } else {
              // 如果rowKey不是数字，尝试根据第一列的值查找
              rowIndex = filteredTableData.rows.findIndex((row: any) => 
                String(row[0]) === rowKey
              );
              if (rowIndex >= 0) {
                const row = filteredTableData.rows[rowIndex];
                const chineseName = row?.[1]?.toString().trim();
                if (chineseName && chineseName !== '' && chineseName !== '—') {
                  parameterName = chineseName;
                }
              }
            }
          }
          
          console.log(`处理参数: key=${key}, rowKey=${rowKey}, rowIndex=${rowIndex}, parameterName=${parameterName}, value=${value}`);
          
          return {
            parameter_name: parameterName,
            parameter_value: value,
            data_type: 'string',
            is_required: false
          };
        });

      console.log('准备保存的参数:', parametersToSave);

      if (parametersToSave.length === 0) {
        toast({ title: "提示", description: "没有要保存的数据" });
        console.log('没有要保存的数据');
        return;
      }

      if (!deviceId) {
        toast({ title: "错误", description: "设备ID为空，无法保存数据", variant: "destructive" });
        console.error('设备ID为空:', deviceId);
        return;
      }

      // 映射参数类型
      const parameterTypeMap = {
        'naming': 'naming',
        'location': 'position', 
        'basic': 'base'
      };
      const apiParameterType = parameterTypeMap[type as keyof typeof parameterTypeMap] || type;

      console.log('API参数类型映射:', type, '->', apiParameterType);

      const requestBody = {
        deviceId: deviceId,
        parameterType: apiParameterType, // 'naming', 'position', 'base'
        parameters: parametersToSave
      };

      console.log('发送请求体:', requestBody);

      // 调用API保存数据
      const response = await fetch('/api/sqlite-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });

      console.log('API响应状态:', response.status);

      if (!response.ok) {
        const errorText = await response.text();
        console.error('API错误响应:', errorText);
        throw new Error(`保存失败: ${response.status} - ${errorText}`);
      }

      const responseData = await response.json();
      console.log('API响应数据:', responseData);

    setSavedData({ ...inputData })
    setIsLocked(true)
    toast({
      title: "保存成功",
        description: "数据已成功保存到数据库",
      })
    } catch (error) {
      console.error('保存数据失败:', error);
      toast({
        title: "保存失败",
        description: "无法保存数据，请重试",
        variant: "destructive",
      });
    }
  }

  // 取消编辑（恢复到保存的数据，清空本次输入）
  const cancelEdit = () => {
    setInputData({ ...savedData })
    setIsLocked(true)
    toast({
      title: "已取消",
      description: "已恢复到之前保存的数据",
    })
  }

  // 开启修改模式
  const enableEdit = () => {
    // 将保存的数据加载到输入框中
    setInputData({ ...savedData })
    setIsLocked(false)
    toast({
      title: "编辑模式",
      description: "现在可以编辑数据了",
    })
  }

  const getTypeTitle = (type: string) => {
    switch(type) {
      case 'naming': return '对象命名'
      case 'location': return '位置信息'
      case 'basic': return '基础参数'
      default: return '参数'
    }
  }

  // 解析工作表内的子表
  const parseSubTables = (sheet: any) => {
    const subTables: Array<{name: string, startRow: number, endRow: number, data: any[]}> = [];
    
    // 首先检查headers中是否有表标题
    if (sheet.headers && sheet.headers[0] && typeof sheet.headers[0] === 'string' && sheet.headers[0].includes('表 C.')) {
      const tableName = sheet.headers[0].trim();
      
      // 智能截断：检测是否混入了其他表的内容
      let cleanedRows = [...sheet.rows];
      if (tableName.includes('C.4')) {
        cleanedRows = detectAndTruncateTableC4(sheet.rows, tableName);
      }
      
      subTables.push({
        name: tableName,
        startRow: 0,
        endRow: cleanedRows.length - 1,
        data: cleanedRows
      });
    }

    // 查找以"表"开头的行作为子表分隔符
    for (let i = 0; i < sheet.rows.length; i++) {
      const row = sheet.rows[i];
      if (row && row[0] && typeof row[0] === 'string' && row[0].includes('表 C.')) {
        const tableName = row[0].trim();
        let endRow = sheet.rows.length - 1;
        
        // 查找下一个表的开始位置
        for (let j = i + 1; j < sheet.rows.length; j++) {
          const nextRow = sheet.rows[j];
          if (nextRow && nextRow[0] && typeof nextRow[0] === 'string' && nextRow[0].includes('表 C.')) {
            endRow = j - 1;
            break;
          }
        }
        
        let tableData = sheet.rows.slice(i, endRow + 1);
        
        // 智能截断：检测是否混入了其他表的内容
        if (tableName.includes('C.4')) {
          tableData = detectAndTruncateTableC4(tableData, tableName);
        }
        
        subTables.push({
          name: tableName,
          startRow: i,
          endRow: i + tableData.length - 1,
          data: tableData
        });
      }
    }

    return subTables;
  };

  // 智能检测并截断表C.4中混入的表C.6内容
  const detectAndTruncateTableC4 = (rows: any[], tableName: string) => {
    if (!rows || !tableName.includes('C.4')) {
      return rows;
    }

    const cleanedRows = [];
    let foundC6Content = false;
    
    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      
      // 检测是否遇到了表C.6的标题或内容
      if (row && row[0] && typeof row[0] === 'string') {
        const cellContent = row[0].toString().trim();
        
        // 检测表C.6的特征标识
        if (cellContent.includes('表 C.6') || 
            cellContent.includes('C.6') || 
            cellContent.includes('LOCO04') ||
            cellContent.includes('位置信息表')) {
          foundC6Content = true;
          console.log(`🔍 检测到表C.4中混入的表C.6内容，在第${i+1}行截断:`, cellContent);
          break;
        }
        
        // 检测其他表的特征（以防有其他表混入）
        if (cellContent.match(/表\s*C\.[5-9]/) && !cellContent.includes('C.4')) {
          foundC6Content = true;
          console.log(`🔍 检测到表C.4中混入的其他表内容，在第${i+1}行截断:`, cellContent);
          break;
        }
      }
      
      // 检测空行连续出现（可能是表间分隔）
      if (i > 5 && isEmptyRow(row)) { // 跳过前5行，避免误判表头空行
        // 检查接下来的几行是否有其他表的内容
        let hasOtherTableContent = false;
        for (let j = i + 1; j < Math.min(i + 5, rows.length); j++) {
          const nextRow = rows[j];
          if (nextRow && nextRow[0] && typeof nextRow[0] === 'string') {
            const nextContent = nextRow[0].toString().trim();
            if (nextContent.includes('表 C.6') || 
                nextContent.includes('LOCO04') ||
                nextContent.match(/表\s*C\.[5-9]/)) {
              hasOtherTableContent = true;
              foundC6Content = true;
              console.log(`🔍 在空行后检测到其他表内容，在第${i+1}行截断:`, nextContent);
              break;
            }
          }
        }
        if (hasOtherTableContent) break;
      }
      
      cleanedRows.push(row);
    }
    
    if (foundC6Content) {
      console.log(`✅ 表C.4数据清理完成，从${rows.length}行截断为${cleanedRows.length}行`);
      
      // 移除末尾的空行
      while (cleanedRows.length > 0 && isEmptyRow(cleanedRows[cleanedRows.length - 1])) {
        cleanedRows.pop();
      }
    }
    
    return cleanedRows;
  };

  // 判断是否为空行
  const isEmptyRow = (row: any[]) => {
    if (!row) return true;
    return row.every(cell => {
      if (cell === null || cell === undefined) return true;
      const str = cell.toString().trim();
      return str === '' || str === '—' || str === '-';
    });
  };

  // 过滤空白列的函数
  const filterEmptyColumns = (data: any) => {
    if (!data || !data.headers || !data.rows) return data;

    const headers = data.headers;
    const rows = data.rows;
    
    // 检查哪些列有实际内容或有效表头
    const validColumns: number[] = [];
    
    for (let colIndex = 0; colIndex < headers.length; colIndex++) {
      const header = headers[colIndex]?.toString().trim();
      
      // 如果表头不为空，就保留这一列（不管数据行是否为空）
      if (header && header !== '' && header !== '—' && header !== '-') {
        validColumns.push(colIndex);
      }
    }
    
    // 如果没有找到有效列，保留所有列
    if (validColumns.length === 0) {
      return data;
    }
    
    // 过滤表头和行数据
    const filteredHeaders = validColumns.map(index => headers[index]);
    const filteredRows = rows.map((row: any[]) => 
      validColumns.map(index => row[index])
    );
    
    return {
      ...data,
      headers: filteredHeaders,
      rows: filteredRows
    };
  };

  // 过滤表格数据的函数
  const filterTableData = (filterType: string) => {
    if (!tableData) return;

    setSelectedFilter(filterType);

    if (filterType === 'all') {
      const filteredData = filterEmptyColumns(tableData);
      setFilteredTableData(filteredData);
      return;
    }

    // 查找数据来源列的索引
    let dataSourceColumnIndex = -1;
    const headers = tableData.headers || [];

    // 查找包含"数据来源"、"来源"等关键词的列
    for (let i = 0; i < headers.length; i++) {
      const header = headers[i]?.toString().toLowerCase() || '';
      if (header.includes('数据来源') || header.includes('来源')) {
        dataSourceColumnIndex = i;
        break;
      }
    }

    // 如果没有找到数据来源列，尝试查找最后几列中可能包含P、E、C、R的列
    if (dataSourceColumnIndex === -1) {
      for (let i = Math.max(0, headers.length - 3); i < headers.length; i++) {
        const header = headers[i]?.toString() || '';
        if (header.length <= 3 && (header.includes('P') || header.includes('E') || header.includes('C') || header.includes('R'))) {
          dataSourceColumnIndex = i;
          break;
        }
      }
    }

    // 根据数据来源过滤数据
    const filtered = {
      ...tableData,
      rows: tableData.rows.filter((row: any[]) => {
        if (dataSourceColumnIndex === -1) {
          // 如果没有找到数据来源列，在所有列中搜索
          const allCells = row.join(' ').toUpperCase();
          return allCells.includes(filterType);
        } else {
          // 在指定的数据来源列中搜索
          const dataSourceCell = row[dataSourceColumnIndex]?.toString().toUpperCase() || '';
          return dataSourceCell.includes(filterType);
        }
      })
    };

    // 对过滤后的数据也应用空白列过滤
    const finalFiltered = filterEmptyColumns(filtered);
    setFilteredTableData(finalFiltered);
  };

  // 数据校核函数
  // 在计量类列后添加计量单位列
  const addMeasurementUnitColumn = (tableData: any) => {
    if (!tableData || !tableData.headers) return tableData;
    
    // 找到计量类列的索引
    const measurementTypeIndex = tableData.headers.findIndex((header: string) => 
      header && header.toString().trim() === '计量类'
    );
    
    if (measurementTypeIndex === -1) {
      return tableData; // 如果没有计量类列，直接返回原数据
    }
    
    // 在计量类列后插入计量单位列
    const newHeaders = [...tableData.headers];
    newHeaders.splice(measurementTypeIndex + 1, 0, '计量单位');
    
    // 为每一行数据添加计量单位
    const newRows = tableData.rows.map((row: any[]) => {
      const newRow = [...row];
      const measurementType = row[measurementTypeIndex];
      const measurementUnit = measurementType === '—' 
        ? '—' 
        : (measurementType && measurementUnitMap[measurementType] 
           ? measurementUnitMap[measurementType] 
           : '');
      newRow.splice(measurementTypeIndex + 1, 0, measurementUnit);
      return newRow;
    });
    
    return {
      ...tableData,
      headers: newHeaders,
      rows: newRows
    };
  };

  // 根据数据类型生成占位符提示
  const getPlaceholderByDataType = (rowData: any[], headers: string[]) => {
    const dataTypeIndex = headers.findIndex(h => h?.toString().toLowerCase().includes('数据类型') || h?.toString().toLowerCase().includes('类型'))
    const dataType = dataTypeIndex >= 0 ? rowData[dataTypeIndex]?.toString().toLowerCase() : ''
    
    // 获取中文名称字段用于坐标识别
    const nameIndex = headers.findIndex(h => h?.toString().includes('中文名称') || h?.toString().includes('名称'))
    const nameValue = nameIndex >= 0 ? rowData[nameIndex]?.toString() : ''
    
    if (dataType.includes('日期')) {
      return 'YYYY-MM-DD'
    } else if (dataType.includes('数值') || dataType.includes('数字')) {
      return '请输入数值'
    } else if (dataType.includes('字符') || dataType.includes('文本')) {
      // 检查是否为坐标相关的行
      if (nameValue && nameValue.includes('坐标')) {
        return '坐标系名称（X坐标，Y坐标，Z坐标）'
      } else {
        return '请输入文本'
      }
    }
    return '请输入数据'
  }

  const validateData = (value: string, rowData: any[], headers: string[]) => {
    if (!value || value.trim() === '') {
      return { isValid: true, message: '', type: 'success' as const }
    }
    
    // 获取数据类型和计量单位
    const dataTypeIndex = headers.findIndex(h => h?.toString().toLowerCase().includes('数据类型') || h?.toString().toLowerCase().includes('类型'))
    const dataType = dataTypeIndex >= 0 ? rowData[dataTypeIndex]?.toString().toLowerCase() : ''
    
    const unitIndex = headers.findIndex(h => h?.toString().toLowerCase().includes('计量单位'))
    const unit = unitIndex >= 0 ? rowData[unitIndex]?.toString() : ''
    
    // 获取中文名称字段用于坐标识别
    const nameIndex = headers.findIndex(h => h?.toString().includes('中文名称') || h?.toString().includes('名称'))
    const nameValue = nameIndex >= 0 ? rowData[nameIndex]?.toString() : ''
    
    // 数据类型校核
    if (dataType.includes('数值') || dataType.includes('数字')) {
      const numValue = parseFloat(value)
      if (isNaN(numValue)) {
        return { isValid: false, message: '数据类型不匹配：应为数值型', type: 'error' as const }
      }
    } else if (dataType.includes('字符') || dataType.includes('文本')) {
      // 检查是否为坐标相关的行
      if (nameValue && nameValue.includes('坐标')) {
        // 坐标格式：坐标系名称（X坐标，Y坐标，Z坐标） - 支持中英文括号和分隔符
        const coordinateRegex = /^[^（()]+[（(]\s*\d+(?:\.\d+)?\s*[，,]\s*\d+(?:\.\d+)?\s*[，,]\s*\d+(?:\.\d+)?\s*[）)]$/
        if (!coordinateRegex.test(value)) {
          return { isValid: false, message: '坐标格式不正确，应为"坐标系名称（X坐标，Y坐标，Z坐标）"', type: 'error' as const }
        }
      } else if (value.length > 50) {
        return { isValid: false, message: '文本长度超限', type: 'warning' as const }
      }
    } else if (dataType.includes('日期')) {
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/
      if (!dateRegex.test(value)) {
        return { isValid: false, message: '日期格式不正确，应为YYYY-MM-DD', type: 'error' as const }
      } else {
        // 进一步校核月和日的有效性
        const [year, month, day] = value.split('-').map(Number)
        if (month < 1 || month > 12) {
          return { isValid: false, message: '月份不正确，应为01-12', type: 'error' as const }
        }
        if (day < 1 || day > 31) {
          return { isValid: false, message: '日期不正确，应为01-31', type: 'error' as const }
        }
        // 对特定月份进行天数校核
        if (month === 2) {
          const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)
          if (day > (isLeapYear ? 29 : 28)) {
            return { isValid: false, message: `二月份天数不正确，${isLeapYear ? '闰年' : '平年'}最多${isLeapYear ? '29' : '28'}天`, type: 'error' as const }
          }
        } else if ([4, 6, 9, 11].includes(month) && day > 30) {
          return { isValid: false, message: '该月份最多30天', type: 'error' as const }
        }
      }
    }
    
    // 计量单位格式校核
    if (unit && unit !== '—' && dataType.includes('数值')) {
      const numValue = parseFloat(value)
      if (!isNaN(numValue)) {
        // 根据计量单位进行特定校核
        if (unit.includes('℃') && (numValue < -50 || numValue > 300)) {
          return { isValid: false, message: '温度值超出合理范围(-50~300℃)', type: 'warning' as const }
        }
        if ((unit.includes('Pa') || unit.includes('MPa') || unit.includes('kPa')) && numValue < 0) {
          return { isValid: false, message: '压力值不能为负数', type: 'error' as const }
        }
        if (unit.includes('r/min') && (numValue < 0 || numValue > 10000)) {
          return { isValid: false, message: '转速值超出合理范围(0~10000 r/min)', type: 'warning' as const }
        }
        if (unit.includes('mm') && numValue < 0) {
          return { isValid: false, message: '长度值不能为负数', type: 'error' as const }
        }
        if (unit.includes('%') && (numValue < 0 || numValue > 100)) {
          return { isValid: false, message: '百分比值应在0~100范围内', type: 'warning' as const }
        }
        if ((unit.includes('m3/h') || unit.includes('L/s') || unit.includes('t/h')) && numValue < 0) {
          return { isValid: false, message: '流量值不能为负数', type: 'error' as const }
        }
      }
    }
    
    return { isValid: true, message: '数据校核通过', type: 'success' as const }
  }

  // 加载表格数据
  useEffect(() => {
    const loadTableData = async () => {
      if (!classificationCode || !tableName) return;

      setLoading(true);
      
      try {
        // 加载分类表Excel文件
        const filename = encodeURIComponent('06-06/0606-石楼油库实体对象分类表.xlsx');
        const response = await fetch(`/api/excel?filename=${filename}`);
        if (!response.ok) {
          throw new Error('加载Excel文件失败');
        }
        const excelData = await response.json();

        // 查找对应的表格数据
        let targetTable = null;

        // 从表名中提取C开头的分类码，如果没有则使用传入的分类码
        let searchCode = classificationCode;
        const cCodeMatch = tableName.match(/表\s*(C\.\d+)/);
        if (cCodeMatch) {
          searchCode = cCodeMatch[1];
        }

        // 在所有工作表中查找包含指定分类码的表
        for (const sheet of excelData.sheets) {
          if (sheet.sheetName.startsWith('C')) {
            // 解析工作表内的子表
            const subTables = parseSubTables(sheet);

            for (const subTable of subTables) {
              // 检查子表名称是否包含搜索的分类码
              if (subTable.name.includes(searchCode)) {
                // 找到实际的表头行
                let actualHeaders = [];
                let actualRows = subTable.data;

                // 查找包含"序号"、"中文名称"等关键词的行作为表头
                for (let i = 0; i < Math.min(3, subTable.data.length); i++) {
                  const row = subTable.data[i];
                  if (row && row[0] && typeof row[0] === 'string' &&
                      (row[0].includes('序号') || row[0].includes('中文名称') || row[0].includes('属性名称'))) {
                    actualHeaders = row;
                    actualRows = subTable.data.slice(i + 1);
                    break;
                  }
                }

                // 如果没找到合适的表头，使用第一行
                if (actualHeaders.length === 0 && subTable.data.length > 0) {
                  actualHeaders = subTable.data[0];
                  actualRows = subTable.data.slice(1);
                }

                targetTable = {
                  name: subTable.name,
                  headers: actualHeaders,
                  rows: actualRows.filter(row => row && row[0] && row[0] !== null && row[0] !== '')
                };
                break;
              }
            }
            if (targetTable) break;
          }
        }

        // 如果没有找到特定的表，显示第一个C开头的表作为默认
        if (!targetTable) {
          for (const sheet of excelData.sheets) {
            if (sheet.sheetName.startsWith('C')) {
              const subTables = parseSubTables(sheet);
              if (subTables.length > 0) {
                const firstTable = subTables[0];

                // 找到实际的表头行
                let actualHeaders = [];
                let actualRows = firstTable.data;

                for (let i = 0; i < Math.min(3, firstTable.data.length); i++) {
                  const row = firstTable.data[i];
                  if (row && row[0] && typeof row[0] === 'string' &&
                      (row[0].includes('序号') || row[0].includes('中文名称') || row[0].includes('属性名称'))) {
                    actualHeaders = row;
                    actualRows = firstTable.data.slice(i + 1);
                    break;
                  }
                }

                if (actualHeaders.length === 0 && firstTable.data.length > 0) {
                  actualHeaders = firstTable.data[0];
                  actualRows = firstTable.data.slice(1);
                }

                targetTable = {
                  name: firstTable.name,
                  headers: actualHeaders,
                  rows: actualRows.filter(row => row && row[0] && row[0] !== null && row[0] !== '')
                };
                break;
              }
            }
          }
        }

        setTableData(targetTable);
        const filteredData = filterEmptyColumns(targetTable);
        
        // 如果是基础参数表，在计量类列后添加计量单位列
        const enhancedData = addMeasurementUnitColumn(filteredData);
        
        setFilteredTableData(enhancedData);
        setSelectedFilter('all');
      } catch (error) {
        console.error('加载表格数据失败:', error);
        toast({
          title: "加载失败",
          description: "无法加载表格数据，请重试",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    };

    loadTableData();
  }, [classificationCode, tableName, toast]);

  // 加载已保存的参数数据
  const loadSavedParameters = async () => {
    if (!deviceId || !type) return;

    try {
      // 映射参数类型
      const parameterTypeMap = {
        'naming': 'naming',
        'location': 'position', 
        'basic': 'base'
      };
      const apiParameterType = parameterTypeMap[type as keyof typeof parameterTypeMap] || type;

      const response = await fetch(`/api/sqlite-parameters?deviceId=${encodeURIComponent(deviceId)}&type=${apiParameterType}`);
      if (response.ok) {
        const savedParameters = await response.json();
        const loadedData: Record<string, string> = {};
        
        // 将保存的参数数据映射到inputData格式
        savedParameters.forEach((param: any) => {
          // 需要找到对应的行键
          if (filteredTableData?.rows) {
            const rowIndex = filteredTableData.rows.findIndex((row: any) => {
              // 获取参数名称，通常在第二列（索引1）
              const paramName = row[1]?.toString().trim();
              const savedParamName = param.parameter_name?.toString().trim();
              return paramName === savedParamName;
            });
            
            if (rowIndex >= 0) {
              // 使用行键或行索引作为键
              const rowKey = (filteredTableData.rows[rowIndex][0] !== undefined && 
                             filteredTableData.rows[rowIndex][0] !== null && 
                             filteredTableData.rows[rowIndex][0] !== '') 
                             ? String(filteredTableData.rows[rowIndex][0]) 
                             : String(rowIndex);
              loadedData[`${rowKey}-数据录入`] = param.parameter_value || '';
            }
          }
        });
        
        setInputData(loadedData);
        setSavedData(loadedData);
      }
    } catch (error) {
      console.error('加载已保存数据失败:', error);
    }
  };

  // 当表格数据加载完成后，加载已保存的参数数据
  useEffect(() => {
    if (filteredTableData && deviceId && type) {
      loadSavedParameters();
    }
  }, [filteredTableData, deviceId, type]);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const userStr = localStorage.getItem('currentUser');
      if (userStr) {
        try {
          const user = JSON.parse(userStr);
          setCurrentUserRole(user.role || 'guest');
        } catch {
          setCurrentUserRole('guest');
        }
      } else {
        setCurrentUserRole('guest');
      }
    }
  }, []);

  const fetchParameters = async () => {
    setLoading(true);
    setFetchError(null);
    try {
      // 类型映射
      const parameterTypeMap = {
        'naming': 'naming',
        'location': 'position',
        'basic': 'base'
      };
      const apiParameterType = parameterTypeMap[type as keyof typeof parameterTypeMap] || type;
      const res = await fetch(`/api/sqlite-parameters?deviceId=${deviceId}&type=${apiParameterType}`);
      const data = await res.json();
      if (!Array.isArray(data)) {
        setParameters([]);
        setFetchError(data?.error || '参数数据加载失败');
      } else {
        setParameters(data);
      }
    } catch (err) {
      setParameters([]);
      setFetchError('参数数据加载异常');
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    if (deviceId && type) fetchParameters();
  }, [deviceId, type]);

  // 页面加载时获取计量单位定义表
  useEffect(() => {
    async function fetchMeasurementUnits() {
      try {
        const res = await fetch('/api/import-measurement-units');
        const data = await res.json();
        if (data.success && Array.isArray(data.data)) {
          // 构建映射表
          const map: Record<string, string> = {};
          data.data.forEach((item: any) => {
            if (item.category && item.unit) {
              map[item.category.trim()] = item.unit.trim();
            }
          });
          setMeasurementUnitMap(map);
        }
      } catch (e) {
        setMeasurementUnitMap({});
      }
    }
    fetchMeasurementUnits();
  }, []);

  useEffect(() => {
    if (parameters.length > 0) {
      const data: Record<string, string> = {};
      parameters.forEach((param) => {
        data[`${param.id}`] = param.parameter_value || '';
      });
      setEditData(data);
      setOriginalData(data);
    }
  }, [parameters]);

  const handleSave = async (updatedParameters: any[]) => {
    try {
      const response = await fetch('/api/sqlite-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          parameters: updatedParameters,
          measurementUnitMap
        }),
      })

      if (!response.ok) {
        throw new Error('保存失败')
      }

      await fetchParameters() // 重新加载数据
    } catch (error) {
      console.error('保存失败:', error)
      throw error
    }
  }

  const handleCancel = () => {
    setEditData(originalData);
    setIsEditing(false);
  };

  return (
    <div className="container mx-auto py-6">
      <div className="mb-4">
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            // 尝试返回上一页，如果失败则跳转到配管专业页面
            try {
              if (window.history.length > 1) {
                router.back()
              } else {
                router.push('/piping')
              }
            } catch (error) {
              console.error('路由跳转失败:', error)
              router.push('/piping')
            }
          }}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回设备列表
        </Button>
      </div>
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold">
          {deviceName}
          {'_'}
          {type === 'naming' ? '对象命名表' : (type === 'position' || type === 'location') ? '位置信息表' : '基础参数表'}
          {'_'}
          {(() => {
            const match = tableName.match(/表\s*C\.(\d+)/);
            if (match) return `C${match[1]}`;
            if (classificationCode) return `C${classificationCode.replace(/表|\.|\s/g, '')}`;
            return '';
          })()}
        </h2>
        <div className="flex items-center gap-4">
          {!isEditing && (
            <Button
              variant="outline"
              size="sm"
              className="edit-save-button"
              onClick={() => setIsEditing(true)}
            >
              编辑
            </Button>
          )}
          {isEditing && (
            <>
              <Button
                variant="default"
                size="sm"
                className="edit-save-button"
                onClick={async () => {
                  try {
                    // 这里需要触发保存逻辑
                    await handleSave(parameters);
                    setIsEditing(false);
                  } catch (error) {
                    console.error('保存失败:', error);
                  }
                }}
              >
                保存
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="cancel-button"
                onClick={() => setIsEditing(false)}
              >
                取消
              </Button>
            </>
          )}
        </div>
      </div>

      <div className="space-y-6">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
              <p className="text-muted-foreground">正在加载参数数据...</p>
            </div>
          </div>
        ) : fetchError ? (
          <div className="text-red-600 font-bold my-8">{fetchError}</div>
        ) : (
          <ParameterTable
            deviceId="1"
            parameters={parameters}
            measurementUnitMap={measurementUnitMap}
            currentUserRole={currentUserRole}
            isEditing={isEditing}
            onSave={handleSave}
            onEditingChange={setIsEditing}
          />
        )}
      </div>
    </div>
  )
} 